package com.zixuan.sina.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zixuan.sina.dao.UserMapper;
import com.zixuan.sina.entity.vo.*;
import com.zixuan.sina.utils.Constant;
import com.zixuan.sina.dao.UserReflectionShipMapper;
import com.zixuan.sina.entity.MessageLog;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.entity.UserRelactionShip;
import com.zixuan.sina.service.UserReflectionShipService;
import com.zixuan.sina.service.UserService;
import com.zixuan.sina.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserReflectionShipServiceImpl extends ServiceImpl<UserReflectionShipMapper, UserRelactionShip> implements UserReflectionShipService {

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;
    @Override
    public Result listReflectShip(String userId, long start, long end) {
        Page<UserRelactionShip> page = new Page<>(start,end);
        QueryWrapper<UserRelactionShip> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        Page<UserRelactionShip> result = baseMapper.selectPage(page, wrapper);
        return Result.ok().data(result);
    }

    @Override
    public Result addFriend(UserRelactionShip userRelactionShip) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(null==principal){
            throw new RuntimeException("请登录后重试");
        }
        userRelactionShip.setId(UUID.randomUUID().toString().replace("-","").toString());
        userRelactionShip.setUserId(principal.getId());
        baseMapper.insert(userRelactionShip);
        userRelactionShip.setId(UUID.randomUUID().toString().replace("-","").toString());
        userRelactionShip.setUserId(userRelactionShip.getFriendId());
        userRelactionShip.setFriendId(principal.getId());
        baseMapper.insert(userRelactionShip);
        return Result.ok().message("操作成功");
    }

    @Override
    public Result applicationReflection(UserRelactionShip userRelactionShip) {
        int row = baseMapper.updateById(userRelactionShip);
        if(row<=0){
            return Result.error().message("操作失败");
        }
        return Result.ok().message("操作成功");
    }

    @Override
    public Result listFriendList(String userId, long start, long end) {
       List<FriendListVo> result =  baseMapper.listFriendList(userId);
        return Result.ok(result);
    }

    @Override
    public void addMessage(MessageLog messageLog) {
        messageLog.setMessageTime(new Date());
        messageLog.setId(UUID.fastUUID().toString(true));
        baseMapper.addMessage(messageLog);
    }

    @Override
    public Result getMessageById(String userId, String friendId) {
       List<MessageLogVo> messageLogs =  baseMapper.getMessageById(userId,friendId);
        for (MessageLogVo messageLog : messageLogs) {
            User userById = userService.findUserById(messageLog.getUserId());
            User friendUser = userService.findUserById(messageLog.getSendId());
            if(null!=userById){
                messageLog.setUserAvatar(userById.getAvatar());
            }
            if(null!=friendUser){
                messageLog.setFriendAvatar(friendUser.getAvatar());
            }


        }
        return Result.ok(messageLogs);
    }

    @Override
    public Result findFriendInfoById(String userId, String friendId) {
        return Result.ok(baseMapper.findFriendInfoById(userId,friendId));
    }

    /**
     * 获取好友申请列表
     * @param userId
     * @param identify
     * @return
     */
    @Override
    public Result getApplicationListByUserId(String userId, int identify,int start,int end) {
        Page<UserRelactionShip> page = new Page<>();
        page.setCurrent(start);
        page.setSize(end);
        Page<UserRelactionShip> pageList=null;
        List<UserRelactionShip> userRelactionShipList=new ArrayList<>();
        QueryWrapper<UserRelactionShip> wrapper = new QueryWrapper<>();
        if(identify==0){
            //我发起的
            pageList =baseMapper.selectPage(page, wrapper.eq("user_id", userId));
        } else if (identify==1) {
            //我收到的
            pageList = baseMapper.selectPage(page, new QueryWrapper<UserRelactionShip>().eq("friend_id", userId));
        }
        assert pageList != null;
        for (UserRelactionShip record : pageList.getRecords()) {
            UserRelactionShipVo userRelactionShipVo = new UserRelactionShipVo();
            User user = userService.findUserById(record.getUserId());
            User friend = userService.findUserById(record.getFriendId());
            if(null!=user){
                userRelactionShipVo.setAvatar(user.getAvatar());
                userRelactionShipVo.setNickName(user.getNickName());
            }
            userRelactionShipVo.setId(record.getId());
            userRelactionShipVo.setUserId(record.getUserId());
            userRelactionShipVo.setFriendId(record.getFriendId());
            userRelactionShipVo.setRelStatus(record.getRelStatus());
            userRelactionShipVo.setAliasName(record.getAliasName());
            userRelactionShipVo.setAliasFriend(record.getAliasFriend());
            userRelactionShipVo.setReqMsg(record.getReqMsg());
            userRelactionShipVo.setCreateTime(record.getCreateTime());
            userRelactionShipVo.setFriendName(friend.getNickName());
            userRelactionShipVo.setFriendAvatar(friend.getAvatar());
            userRelactionShipList.add(userRelactionShipVo);
        }
        pageList.setRecords(userRelactionShipList);
        return Result.ok(pageList);
    }

    @Override
    public Result getApplicationCount(String userId) {
        QueryWrapper<UserRelactionShip> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).or().eq("friend_id",userId);
        wrapper.eq("rel_status",Constant.INIT_APPLICATION);

        long count = baseMapper.selectCount(wrapper);
        return Result.ok(count);
    }

    @Override
    @Transactional
    public Result handleApplication(UserRelactionShipVo userRelactionShipVo) {
        UserRelactionShip userRelactionShip = new UserRelactionShip();
        //如果是同意状态 需要建立好友关系 即插入数据库
        BeanUtils.copyProperties(userRelactionShipVo,userRelactionShip);
        int count= baseMapper.selectConnectShip(userRelactionShip);
        if(count==0 && userRelactionShipVo.getRelStatus()== Constant.AGREE_APPLICATION){
            int r =  baseMapper.createFriendShip(userRelactionShip);
            String userId = userRelactionShip.getUserId();
            String friendId = userRelactionShip.getFriendId();

            userRelactionShipVo.setUserId(friendId);
            userRelactionShipVo.setFriendId(userId);
            userRelactionShipVo.setId(UUID.randomUUID().toString().replace("-",""));
             r =  baseMapper.createFriendShip(userRelactionShipVo);
        }
        userRelactionShip.setRelStatus(userRelactionShipVo.getRelStatus());
         int row = baseMapper.updateById(userRelactionShip);

        return Result.ok(row>0?"操作成功":"操作失败");
    }

    @Override
    public Result isFriendRelation(String userId, String friendId) {
       Long count =  baseMapper.isFriendRelation(userId,friendId);
        return Result.ok(count);
    }

    @Override
    public List<UserFriend> getFriendByUserId() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(null==principal){
            throw new RuntimeException("请登录后重试");
        }
        LambdaQueryWrapper<UserRelactionShip> wrapper=new LambdaQueryWrapper<>();

        wrapper.eq(UserRelactionShip::getUserId,principal.getId());
        List<UserRelactionShip> userRelactionShipList = baseMapper.selectList(wrapper);
        List<UserFriend> collect = userRelactionShipList.stream().map(m -> {
            User userById = userService.findUserById(m.getFriendId());
            //查询最近消息预览
            List<MessageLog> messagePreview = baseMapper.getMessagePreview(principal.getId(), m.getFriendId());
            UserFriend userFriend = new UserFriend();
            userFriend.setNickName(StrUtil.isBlank(userById.getNickName())?userById.getRealName(): userById.getNickName());
            userFriend.setFriendId(userById.getId());
            userFriend.setAvatar(userById.getAvatar());
            if(!CollUtil.isEmpty(messagePreview)){
                String messagePreviewStr=messagePreview.get(0).getMessage();
                if(messagePreview.get(0).getMessage().length()>20){
                    messagePreviewStr=messagePreviewStr.substring(0,19)+"...";
                }
                userFriend.setPreview(messagePreviewStr);
            }else {
                userFriend.setPreview("暂无消息");
            }

            messagePreview=messagePreview.stream().sorted(Comparator.comparing(MessageLog::getMessageTime)).collect(Collectors.toList());
            List<UserFriend.Message> collect1 = messagePreview.stream().map(message -> {
                UserFriend.Message messageLog = new UserFriend.Message();
                messageLog.setText(message.getMessage());
                messageLog.setTime(DateUtil.format(message.getMessageTime(), "YYYY-MM-dd HH:mm:ss"));
                messageLog.setOwn(message.getUserId().equals(principal.getId()) ? true : false);
                return messageLog;
            }).collect(Collectors.toList());
            userFriend.setMessages(collect1);
            return userFriend;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public List<MessageLog> getFriendMessage(Long friendId) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(null==principal){
            throw new RuntimeException("请登录后重试");
        }
        List<MessageLog> messagePreview = baseMapper.getMessagePreview(principal.getId(), String.valueOf(friendId));
       return messagePreview.stream().sorted(Comparator.comparing(MessageLog::getMessageTime)).collect(Collectors.toList());
    }

    @Override
    public List<FriendVo> listFriend(String key) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(null==principal){
            throw new RuntimeException("请登录后重试");
        }
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        if(!StrUtil.isBlank(key)){
            wrapper.eq(User::getUsername,key);
            wrapper.eq(User::getNickName,key);
        }
        List<User> users = userMapper.selectList(wrapper);
        List<FriendVo> friendVos = users.stream().filter(f->!(principal.getId().equals(f.getId()))).map(m -> {
            LambdaQueryWrapper<UserRelactionShip> userRelactionShipLambdaQueryWrapper=new LambdaQueryWrapper<>();
            userRelactionShipLambdaQueryWrapper.eq(UserRelactionShip::getUserId, principal.getId());
            FriendVo friendVo = new FriendVo();
            friendVo.setNickName(m.getNickName());
            friendVo.setRealName(m.getRealName());
            friendVo.setUserId(m.getId());
            friendVo.setAvatar(m.getAvatar());
            //查询是否属于好友关系
            userRelactionShipLambdaQueryWrapper.eq(UserRelactionShip::getFriendId, m.getId());
            Long count = baseMapper.selectCount(userRelactionShipLambdaQueryWrapper);
            friendVo.setAccepted(count > 0);
            return friendVo;
        }).collect(Collectors.toList());

        return friendVos;
    }
}
